package com.birdboot.core;

import com.birdboot.annotations.Controller;
import com.birdboot.annotations.RequestMapping;
import com.birdboot.http.HttpServletRequest;
import com.birdboot.http.HttpServletResponse;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URI;
import java.net.URISyntaxException;

public class DispatcherServlet {

    static File baseDir;
    static File staticDir;

    static {
        try {
            baseDir = new File(HandlerMapping.class.getClassLoader().getResource(".").toURI());
            staticDir = new File(baseDir,"static");
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }

    }
    public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {

        String path = request.getUri();
        System.out.println("path:"+path);
        Method method = HandlerMapping.getMethod(path);
        if(method!=null){
            Class cls = method.getDeclaringClass();
            try {
                Object obj = cls.newInstance();
                method.invoke(obj,request,response);
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }else{
            File file = new File(staticDir,path);
            if(file.isFile()){
                response.setContentFile(file);
                response.addHeader("Server","BirdServer");
            }else{
                response.setCodeStatus(404);
                response.setStatusReason("NotFound");
                file = new File(staticDir,"404.html");
                response.setContentFile(file);
                response.addHeader("Server","BirdServer");
            }
            response.Response();
        }
    }
}
